package com.schoolcloud.files.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.files.entity.FileMain;
import com.schoolcloud.files.query.FileMainQuery;
import com.schoolcloud.files.service.FileMainService;
import com.schoolcloud.files.mapper.FileMainMapper;
import com.schoolcolud.daomybatisplus.dto.MpPageUtil;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author hongmizfb
 * @description 针对表【file_main(文件主表)】的数据库操作Service实现
 * @createDate 2025-07-19 16:18:37
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FileMainServiceImpl extends ServiceImpl<FileMainMapper, FileMain>
        implements FileMainService {
    private final MinioClient minioClient;

    @Override
    public FileMain getByFilePath(String filePath) {
        //  todo       考虑到文件路径可能带有前缀，所以这里要判断一下，但是不应该这样写，后续有时间优化一线
        return lambdaQuery().eq(FileMain::getStoragePath, filePath).or().eq(FileMain::getVisitPath, filePath).one();
    }

    @Override
    public PageDTO<FileMain> getFilePage(FileMainQuery query) {
        Page<FileMain> page = lambdaQuery().eq(query.getFilePath() != null, FileMain::getStoragePath, query.getFilePath())
                .eq(query.getStorageBucket() != null, FileMain::getStorageBucket, query.getStorageBucket())
                .like(query.getOriginalName() != null, FileMain::getOriginalName, query.getOriginalName())
                .page(query.toMpPage());
        return MpPageUtil.of(page, FileMain.class);
    }

    @Override
    public FileMain getByMd5(String md5) {
        return lambdaQuery().eq(FileMain::getMd5, md5).one();
    }

    @Override
    public void deleteFileById(Integer id) {
        FileMain byId = getById(id);
        if (byId != null) {
            try {
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(byId.getStorageBucket()).object(byId.getStoragePath()).build());
                removeById(id);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除文件失败:文件Id:{}，失败信息:{}", byId.getId(), e.getMessage());
            }
        }

    }
}




